package com.atguigu.petstore.sys.biz.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.petstore.common.constant.RedisConst;
import com.atguigu.petstore.common.execption.PetstoreException;
import com.atguigu.petstore.common.result.ResultCodeEnum;
import com.atguigu.petstore.common.util.MD5;
import com.atguigu.petstore.sys.biz.SysLoginService;
import com.atguigu.petstore.sys.entity.SysUser;
import com.atguigu.petstore.sys.service.SysUserService;
import com.atguigu.petstore.sys.vo.SysLoginResp;
import com.atguigu.petstore.sys.vo.SysLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lfy
 * @Description
 * @create 2023-09-22 9:03
 */
@Service
public class SysLoginServiceImpl implements SysLoginService {


    @Autowired
    SysUserService sysUserService;

    @Autowired //禁用底层的默认序列化转换行为，我们自己转
    StringRedisTemplate redisTemplate;



    @Override
    public SysLoginResp login(SysLoginVo loginVo) {

        //1、校验验证码，
        boolean captcha = checkCaptcha(loginVo.getDeviceId(), loginVo.getCode());
        if(!captcha){
            //非法的逻辑校验
            throw new PetstoreException(ResultCodeEnum.USER_CAPTCHA_INVAILD);
        }



        //2、验证码通过，数据库查询这个用户是否存在
        String encrypt = MD5.encrypt(loginVo.getPassword());
        SysUser user = sysUserService.lambdaQuery()
                .eq(SysUser::getLoginName, loginVo.getAccount())
                .eq(SysUser::getLoginPwd, encrypt)
                .eq(SysUser::getAccountStatus,1)
                .one();

        //3、如果不存在
        if(user==null){
            throw new PetstoreException(ResultCodeEnum.USER_ACCOUNT_PWD_ERROR);
        }


        //4、登录成功，生成唯一令牌，交给前端
        String token = UUID.randomUUID().toString().replace("-", "");

        //5、登录成功, 按照这个令牌去redis保存登录信息  user:login:你的令牌 = SysUser的json
        String key = RedisConst.USER_LOGIN_KEY + token;
        //6、7天免登录；（前端这7天内，带这个令牌过来）
        redisTemplate.opsForValue().set(key, JSON.toJSONString(user),7, TimeUnit.DAYS);


        //7、把令牌交给前端

        SysLoginResp resp = new SysLoginResp();
        resp.setToken(token);
        resp.setUser(user);

        return resp;
    }

    @Override
    public boolean checkCaptcha(String deviceId,String captcha) {
        //要求：所有的前端，都有它的唯一设备id；由前端自己生成我们不管

        //redis有，且删除这个， 不区分大小写
        String key = RedisConst.CAPTCHA_KEY +deviceId + ":" + captcha.toLowerCase();

        return redisTemplate.delete(key);
    }

    @Override
    public void checkToken(String token) {
        Boolean hasKey = redisTemplate.hasKey(RedisConst.USER_LOGIN_KEY + token);
        if(!hasKey){
            throw new PetstoreException(ResultCodeEnum.USER_INVAILD);
        }
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY + token);
    }
}
